<template>
  <div>
    <Header />
    <Menu />
    <div v-if="showPageContent" class="container-fluid">
      <div class="row text-center justify-content-center webtitle"></div>
      <div class="row justify-content-center">
        <div class="avatar-uploader-container">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
        <div class="row">
          <p class="upload-tip">点击小说封面图片可以更换</p>
        </div>
        <el-form ref="novelForm" :model="form" label-width="auto" @submit.prevent="updateNovel" style="max-width: 90%">

          <el-form-item label="小说名称" prop="novel_name">
            <el-input v-model="form.novel_name" clearable required></el-input>
          </el-form-item>
          <el-form-item label="小说描述" prop="novel_desc">
            <el-input
                type="textarea"
                v-model="form.novel_desc"
                clearable
                required
            ></el-input>
          </el-form-item>
          <el-form-item label="小说类型" prop="novel_type">
            <el-input v-model="form.novel_type" required clearable></el-input>
          </el-form-item>
          <el-form-item label="小说图片链接" prop="novel_pic" v-if="!isPicInputHidden">
            <el-input v-model="form.novel_pic" clearable disabled></el-input>
          </el-form-item>
<!--          <el-form-item label="小说图片链接" v-if="imageUrl">
            <el-input v-model="form.novel_pic" clearable disabled></el-input>
          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" native-type="submit">更新小说</el-button>
            <el-button type="danger" @click="confirmDelete">删除小说</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import VueCookies from "vue-cookies";
import { ElNotification, ElMessageBox } from "element-plus";
import { Plus } from '@element-plus/icons-vue';
import Header from "@/components/Header.vue";
import Menu from "@/components/Menu.vue";
import config from "../../../config/config.js";

const showPageContent = ref(true);
const form = ref({
  novel_name: '',
  novel_desc: '',
  novel_type: '',
  novel_pic: ''
});
const uploadUrl = ref(`${config.apiUrl}/upload/images`);

const route = useRoute();
const router = useRouter();

const fetchNovelInfo = async () => {
  const novelId = route.params.novelId;
  const userToken = VueCookies.get('userToken');
  const apiUrl = `${config.apiUrl}/novel/info?novelId=${novelId}`;
  const headers = {
    Authorization: `Bearer ${userToken}`
  };

  try {
    const response = await axios.get(apiUrl, { headers });
    const novelInfo = response.data;
    if (response.status === 201) {
      ElNotification({
        message: novelInfo.message,
        type: 'warning',
        duration: 2000
      });
      showPageContent.value = false;
    } else {
      form.value.novel_name = novelInfo.novel_name;
      form.value.novel_desc = novelInfo.novel_desc;
      form.value.novel_type = novelInfo.novel_type;
      form.value.novel_pic = novelInfo.novel_pic;
      if (novelInfo.novel_pic) {
        imageUrl.value = novelInfo.novel_pic;
        isPicInputHidden.value = true;
      }
    }
  } catch (error) {
    console.error('获取小说信息失败:', error);
    ElNotification({
      message: '暂无信息',
      type: 'warning',
      duration: 2000
    });
    router.back(); // 自动返回
  }
};

const imageUrl = ref('');
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = response.filePath;
  form.value.novel_pic = response.filePath;
  ElNotification({
    message: '上传成功！',
    type: 'success',
    duration: 2000
  });
};

const beforeAvatarUpload = (rawFile) => {
  const allowedExtensions = ['png', 'jpg', 'webp'];
  const extension = rawFile.name.split('.').pop();
  if (!allowedExtensions.includes(extension)) {
    ElNotification({
      message: '无效文件: Invalid file extension',
      type: 'error',
      duration: 2000
    });
    return false;
  }
  return true;
};

const updateNovel = async () => {
  const novelId = route.params.novelId;
  const userToken = VueCookies.get('userToken');
  const apiUrl = `${config.apiUrl}/novel/update?novelId=${novelId}`;
  const headers = {
    Authorization: `Bearer ${userToken}`
  };

  try {
    const response = await axios.post(apiUrl, form.value, { headers });
    if (response.status === 200) {
      ElNotification({
        message: response.data.message,
        type: 'success',
        duration: 2000
      });
    } else {
      ElNotification({
        message: response.data.message,
        type: 'error',
        duration: 1400
      });
    }
  } catch (error) {
    ElNotification({
      message: error,
      type: 'error',
      duration: 2000
    });
  }
};

const deleteNovel = async () => {
  const novelId = route.params.novelId;
  const userToken = VueCookies.get('userToken');
  const apiUrl = `${config.apiUrl}/novel/delete?novelId=${novelId}`;
  const headers = {
    Authorization: `Bearer ${userToken}`
  };

  try {
    const response = await axios.get(apiUrl, { headers });
    if (response.status === 200) {
      ElNotification({
        message: response.data.message,
        type: 'success',
        duration: 2000
      });
      router.back(); // 返回上一页
    } else {
      ElNotification({
        message: response.data.message,
        type: 'error',
        duration: 1400
      });
    }
  } catch (error) {
    ElNotification({
      message: error,
      type: 'error',
      duration: 2000
    });
  }
};

const goBack = () => {
  router.back();
};

const confirmDelete = () => {
  ElMessageBox.confirm('删除小说会同时删除该小说下的所有章节！', '确定删除？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteNovel();
  });
};

const isPicInputHidden = ref(false);

onMounted(fetchNovelInfo);
</script>

<style scoped>
.webtitle {
  font-size: 20px;
  padding: 10px;
}
.avatar-uploader-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar-uploader .avatar {
  width: 128px;
  height: 160px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 178px;
  text-align: center;
  border:1px dotted lightgrey;
}
.upload-tip {
  text-align: center;
  margin-top: 10px;
  font-size: 12px;
  color:grey;
}
</style>
